<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="用户列表"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')" v-permission="'systemUserAdd'">新增</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <!-- <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button> -->
        <el-button
          type="primary"
          link
          :icon="EditPen"
          @click="openDrawer('编辑', scope.row)"
          v-if="!scope.row.isSuperAdmin"
          v-permission="'systemUserEdit'"
          >编辑</el-button
        >
        <el-button
          type="danger"
          link
          :icon="Delete"
          v-if="!scope.row.isSuperAdmin"
          v-permission="'systemUserDelete'"
          @click="deleteUser(scope.row)"
          >删除</el-button
        >
        <el-button
          type="success"
          link
          :icon="User"
          v-if="!scope.row.isSuperAdmin"
          v-permission="'systemUserAuthRole'"
          @click="authRole(scope.row.userId)"
          >分配角色</el-button
        >
      </template>
    </ProTable>
    <UserDialog ref="drawerRef" />
  </div>
</template>

<script setup lang="tsx" name="systemUser">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";

import { SystemUser } from "@/api/interface/systemUser";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";

import UserDialog from "@/views/system/components/UserDialog.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, User } from "@element-plus/icons-vue";
import { getUserListApi, changeUserStatusApi, addUserApi, editUserApi, deleteUserApi } from "@/api/modules/systemUser";
import { roleStatus } from "@/utils/serviceDict";
import { useAuthPermissions } from "@/hooks/useAuthPermissions";

const router = useRouter();

const { PERMISSIONS } = useAuthPermissions();

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.rows,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.beginTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1].replace("00:00:00", "23:59:59"));
  delete newParams.createTime;
  return getUserListApi(newParams);
};

// 表格配置项
const columns: ColumnProps<SystemUser.UserRes>[] = [
  {
    prop: "userId",
    label: "用户编号"
  },
  {
    prop: "account",
    label: "用户账号",
    search: { el: "input" }
  },

  {
    prop: "nickName",
    label: "用户昵称",
    search: { el: "input" }
  },
  {
    prop: "email",
    label: "邮箱"
  },
  {
    prop: "phoneNumber",
    label: "手机号码"
  },
  {
    prop: "status",
    label: "状态",
    enum: roleStatus,
    search: { el: "select", props: { filterable: true } },
    render: scope => {
      return (
        <>
          {PERMISSIONS.value.systemUserChangeStatus && !scope.row.isSuperAdmin ? (
            <el-switch
              model-value={scope.row.status}
              active-value={1}
              inactive-value={0}
              onClick={() => changeStatus(scope.row)}
            />
          ) : (
            <el-tag type={scope.row.status == 1 ? "success" : "danger"}>{scope.row.status == 1 ? "启用" : "禁用"}</el-tag>
          )}
        </>
      );
    }
  },
  {
    prop: "createTime",
    label: "创建时间",
    search: {
      el: "date-picker",
      props: { type: "daterange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 240 }
];

// 切换用户状态
const changeStatus = async (params: SystemUser.UserRes) => {
  await useHandleData(
    changeUserStatusApi,
    { userId: params.userId, status: params.status == 1 ? 0 : 1 },
    `更改【${params.nickName}】用户状态`
  );
  proTable.value?.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDialog> | null>(null);
const openDrawer = (title: string, row: Partial<SystemUser.UserRes> = {}) => {
  const params = {
    title,
    isView: title === "查看" || row.isSuperAdmin === true,
    row: { ...row },
    api: title === "新增" ? addUserApi : title === "编辑" ? editUserApi : undefined,
    getTableList: proTable.value?.getTableList,
    userId: row.userId
  };
  drawerRef.value?.acceptParams(params);
};

// 删除用户
const deleteUser = async (params: SystemUser.UserRes) => {
  await useHandleData(deleteUserApi, params.userId, `删除【${params.nickName}】用户`);
  proTable.value?.getTableList();
};

// 分配角色
const authRole = (userId: number) => {
  router.push(`/system/user/authRole?userId=${userId}`);
};
</script>
